// import baseConfig from './config.js'
class websocket {
	constructor(url) {
		this.is_open_socket = false //避免重复连接
		this.user_empower_close = false
		// this.url = `${baseConfig.webscoketUrl + url}` //地址
		this.url = 'wss://jtmckj.cn:9995/websocket' //地址 wss://jtmckj.com:9996/websocket
		this.data = null

		try {
			return this.connectSocketInit('first')
		} catch (e) {
			this.is_open_socket = false
			this.reconnect('next');
		}
	}

	// 进入这个页面的时候创建websocket连接【整个页面随时使用】
	connectSocketInit(type) {
		this.socketTask = uni.connectSocket({
			url: this.url,
			success: () => {
				console.log("正准备建立websocket中...");
				// 返回实例
				return this.socketTask
			},
		});
		//监听是否连接成功
		this.socketTask.onOpen((res) => {
			console.log('res：',res)
			console.log(type == 'first' ? "WebSocket连接正常！" : "WebSocket重连成功");
			if(type == 'first'){
				const shopInfo = {
					msgContent: {
						brandCode: "0005",
						consumeCode: "",
						cuttrentStateCode: "3",
						cuttrentStateName: "点单就餐",
						memberCode: "M00050000318",
						memberName: "微187****0108",
						orgCode: "0018",
						orgName: "上海空白区",
						roomCode: "0018018",
						roomName: "B07"
					},
					msgPlatform: 3,
					msgType: "heartbeat" 
				};
				this.send(shopInfo);
			}
			this.is_open_socket = true;
			// 注：只有连接正常打开中 ，才能正常收到消息
			this.onConnected()
		})
		// 这里仅是事件监听【如果socket关闭了会执行】关闭重新连接
		this.socketTask.onClose((e) => {
			this.is_open_socket = false;
			if (!this.user_empower_close) {
				this.reconnect('next');
			}
		})
	}

	//发送消息
	send(value) {
		// 注：只有连接正常打开中 ，才能正常成功发送消息
		this.socketTask.send({
			data: value,
			async success(res) {
				console.log("消息发送成功", res);
			},
			async fail(e) {
				console.log("消息发送失败", e);
			}
		});
	}
	//重新连接
	reconnect(type = "next") {
		this.onReconnect()
		//如果关闭的话，进行重连
		if (!this.is_open_socket) {
			this.connectSocketInit(type);
		}
	}
	//外部获取消息
	getMessage(callback) {
		this.socketTask.onMessage((res) => {
			return callback(res)
		})
	}
	//关闭连接
	close(e) {
		this.is_open_socket = false
		if (e.reason == "用户自己关闭") {
			this.user_empower_close = true
			this.socketTask.close({
				async success(res) {
					console.log("关闭成功", e);
				},
				async fail(e) {
					console.log("关闭失败", e);
				}
			})
		} else {
			this.user_empower_close = false
		}

	}
	/**
	 * 重新连接时触发
	 */
	onReconnect() {
		console.log('WebSocket重新连接');
	}
	/**
	 * 连接成功时触发
	 */
	onConnected() { 
		console.log('WebSocket连接已打开 111 1 11');
		
	}
	/**
	 * 断开时触发
	 */
	onClosed() {
		console.log('已断开连接')
	}
	//监听socket转态
	onSocketStatus(callback) {
		return callback(this.is_open_socket ? 'Connecting' : 'Disconnected')
	}
}

export default websocket;